package com.catcoin.consume.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.catcoin.consume.model.Account;
import com.catcoin.consume.mapper.AccountMapper;
import com.catcoin.consume.model.LogMailcc;
import com.catcoin.consume.model.User;
import com.catcoin.consume.result.Result;
import com.catcoin.consume.service.IAccountService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.catcoin.consume.service.ILogMailccService;
import com.catcoin.consume.service.IUserService;
import com.catcoin.consume.util.HttpUtil;
import com.catcoin.consume.util.StringUtils;
import org.apache.http.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreConnectionPNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户账户表 服务实现类
 * </p>
 *
 * @author consume
 * @since 2018-09-03
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Autowired
    private  AccountMapper accountMapper;

    @Autowired
    private ILogMailccService logMailccService;
    @Autowired
    private IUserService userService;
    @Override
    public Result balance(Integer pageNum, Account account) {
        PageHelper.startPage(Integer.valueOf(pageNum),15);
        List<Map<String,Object>> accountlist= new ArrayList<>();
        accountlist=accountMapper.selectAccountByUserId(account);
        List<Object> list = new ArrayList<>();
        if (accountlist.size()>0) {
            for (Map<String,Object> accountMap : accountlist) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", accountMap.get("userId"));
                map.put("cash", accountMap.get("cash"));
                map.put("HHTBC", accountMap.get("HHTBC"));
                map.put("HHTBE", accountMap.get("HHTBE"));
                map.put("statedcc", accountMap.get("statedcc"));
                map.put("blancecc", accountMap.get("blancecc"));
                map.put("mailcc", accountMap.get("mailcc"));
                map.put("moneycc", accountMap.get("moneycc"));
                map.put("ieterestcc", accountMap.get("ieterestcc"));
               if (Integer.parseInt(accountMap.get("status").toString())== 1) {
                    map.put("status", "开启");
                }else {
                    map.put("status", "锁定");
                }
                list.add(map);
            }
        }
        return Result.OK(list,"查询成功!");
    }

    @Override
    public Account selectByUserId(Integer userId) {
        return accountMapper.selectByUserId(userId);
    }

    @Override
    public List<Account> getAccount(Integer userId) {
        EntityWrapper<Account> ew = new EntityWrapper<Account>();
        ew.where("userId={0}",userId);
        ew.and("status = {0}",1);
        List<Account> list = accountMapper.selectList(ew);
        return list;
    }
@Override
@Transactional
    public Map<String,Object> transferTomaill(String userIds, BigDecimal mailccMoney) throws  Exception{
         Map<String,Object> map=new HashMap<>();
        try{

            if (userIds==null|| "".equals(userIds)){
                map.put("code","00");
                map.put("msg","没有登录，请重新登录");
                return map;
            }
            Integer userId=Integer.parseInt(userIds);
            Account account=new Account();
            account.setUserId(userId);
            EntityWrapper<Account> entityWrapper=new  EntityWrapper<Account>(account);
            Account account1 = this.selectOne(entityWrapper);
            BigDecimal mailcc = account1.getMailcc();
            if (mailcc.compareTo(mailccMoney)==-1){
                map.put("code","00");
                map.put("msg","消费账户余额不足");
                return map;
            }
            String orderNo = StringUtils.getOrderIdByTime("M");
            LogMailcc logMailcc = logMailccService.getLogMailcc(userId, userId, orderNo, account1.getMailcc(), mailccMoney, -1, "转至华猫商城", 4);
            logMailccService.insert(logMailcc);
            account1.setMailcc(account1.getMailcc().subtract(mailccMoney));
            this.updateById(account1);
            //调用第三方接口
            String  url="http://localhost:8080/shopping/addShopping";
            User user = userService.selectById(userId);
            Map<String,Object> paraMap = new HashMap<>();
            String userPhone = user.getUserPhone();
            JSONObject jsonObj=new JSONObject();
            paraMap.put("userPhone",userPhone);
            paraMap.put("type",1);
            paraMap.put("money",mailccMoney);
            paraMap.put("sceneType",1);
            String result = HttpUtil.doPost(url, paraMap);

            //转换成json
                JSONObject jsonObject = JSONObject.parseObject(result);
                if("200".equals(jsonObject.get("messageCode").toString())){
                    map.put("code","01");
                    map.put("msg","操作成功");
                    return map;
                }else{
                    map.put("code","00");
                    map.put("msg",jsonObject.get("message").toString());
                    return map;
                }

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code","00");
            map.put("msg","操作异常");
            return map;
        }
    }
}
